//
//  BZUCRegisterV.m
//  Pods
//
//  Created by quheng on 2017/8/29.
//
//

#import "BZUCRegisterV.h"
#import <Masonry/Masonry.h>
#import "BZUCInputV.h"
#import "BZUCInputVModel.h"
#import <BZBaseWidget/BZBaseWidget.h>
#import "BZUCIdentityBtnV.h"
#import "NSString+NormalRegex.h"
#import "BZUCLoginService.h"
#import <YYKit/NSString+YYAdd.h>
#import "UIView+ViewController.h"
#import "BZUCCurrentUser.h"
#import "UIView+ViewController.h"
#import "BZUCProtocolVC.h"
#import <AFNetworking/AFNetworking.h>
#import <BZDataBaseSDK/BZDataBaseSDK.h>

@interface BZUCRegisterV()<BZUCInputVDelegate>


@property (nonatomic, strong) BZUCLoginService *registerService;

@end

@implementation BZUCRegisterV



- (BZUCLoginService *)registerService{

    if (!_registerService) {
        
        _registerService = [[BZUCLoginService alloc]init];
    }
    return _registerService;
}


- (instancetype)init{

    self = [super init];
    
    if (self) {
        
        [self configureV];
    }

    return self;
}




- (void)configureV{


    NSMutableArray *arr = [NSMutableArray arrayWithCapacity:5];
    
    for (NSUInteger i = 0; i<5; i++) {
        
        BZUCInputV *inputV = [[BZUCInputV alloc]init];
        inputV.index = i;
        inputV.delegate = self;
        [self addSubview:inputV];
        
        [inputV mas_makeConstraints:^(MASConstraintMaker *make) {
            
            make.left.equalTo(self).with.offset(16);
            make.right.equalTo(self).with.offset(-16);
            make.top.equalTo(self).with.offset(44*i+30);
            make.height.mas_offset(44);
        }];
        
        [arr addObject:inputV];
    }
    
    self.inputArr = [arr copy];
    
    BZUCIdentityBtnV *identityBtn = [[BZUCIdentityBtnV alloc]init];
    [self addSubview:identityBtn];
    
    BZUCIdentityBtnV *sectBtn = [[BZUCIdentityBtnV alloc]init];
    [self addSubview:sectBtn];
    
    UIButton *registerBtn = [[UIButton alloc]init];
    [registerBtn setTitle:@"注册" forState:UIControlStateNormal];
    [registerBtn addTarget:self action:@selector(clickRegisterBtn:) forControlEvents:UIControlEventTouchUpInside];
    [registerBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [registerBtn.titleLabel setFont:[UIFont systemFontOfSize:15]];
    registerBtn.layer.cornerRadius  = 8;
    registerBtn.layer.masksToBounds = YES;
    registerBtn.backgroundColor = [UIColor colorWithRed:1.00 green:0.42 blue:0.12 alpha:1.00];
    [self addSubview:registerBtn];
    self.registerBtn = registerBtn;
    
    UIButton *protocolBtn = [[UIButton alloc]init];//(r:0.35 g:0.18 b:0.07 a:1.00)
    [protocolBtn setTitle:@"我已阅读并同意《掌中佛服务协议》" forState:UIControlStateNormal];
    protocolBtn.titleLabel.font = [UIFont systemFontOfSize:12];
    [protocolBtn addTarget:self action:@selector(enterProtocolVC:) forControlEvents:UIControlEventTouchUpInside];
    [protocolBtn setTitleColor:[UIColor colorWithRed:0.35 green:0.18 blue:0.07 alpha:1.00] forState:UIControlStateNormal];
//    protocolBtn.titleLabel.textColor = [UIColor colorWithRed:0.35 green:0.18 blue:0.07 alpha:1.00];
    [self addSubview:protocolBtn];
    
    
    [identityBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.equalTo(self).with.offset(16);
        make.right.equalTo(self).with.offset(-16);
        make.height.mas_offset(0);//暂时设为0，不用
        make.top.equalTo(self).with.offset(44*5+30);
    }];
    
    [sectBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.equalTo(self).with.offset(16);
        make.right.equalTo(self).with.offset(-16);
        make.height.mas_offset(0);
        make.top.equalTo(identityBtn.mas_bottom);
    }];
    
    [registerBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(sectBtn.mas_bottom).with.offset(40);
        make.left.equalTo(self).with.offset(58);
        make.right.equalTo(self).with.offset(-58);
        make.height.mas_offset(44);//暂时设为0，不用
    }];
    
    [protocolBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(registerBtn.mas_bottom).with.offset(30);
        make.width.mas_offset(200);
        make.height.mas_offset(20);
        make.centerX.equalTo(self);
    }];
}


- (void)enterProtocolVC:(UIButton *)sender{

    BZUCProtocolVC *protocolVC = [[BZUCProtocolVC alloc]init];
    [[self viewController].navigationController pushViewController:protocolVC animated:YES];

}

- (void)clickRegisterBtn:(UIButton *)sender{

//    if (![AFNetworkReachabilityManager sharedManager].reachable) {
//        [MBProgressHUD showClueInView:self title:@"无网络" duration:0.75];
//        return;
//    }
    
    
    [self endEditing:YES];

   AFNetworkReachabilityStatus status = [AFNetworkReachabilityManager sharedManager].networkReachabilityStatus;
    if (status == AFNetworkReachabilityStatusNotReachable) {
        [MBProgressHUD showClueInView:self title:@"无网络" duration:0.75];
        return;
    }
    
    
    
    NSMutableDictionary *param = [NSMutableDictionary dictionaryWithCapacity:5];
    NSString *oldPassword = @"";
    for (NSUInteger i = 0; i<5; i++) {
        
        BZUCInputV *inputV = self.inputArr[i];
        inputV.textF.text = [inputV.textF.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
        if (![inputV.textF.text length]) {

            if (i == 0) {
                [MBProgressHUD showClueInView:self title:@"请输入手机号" duration:0.7];
                break;
            }else if (i == 1){
                [MBProgressHUD showClueInView:self title:@"请输入验证码" duration:0.7];
                break;
            }else if (i == 2){
                [MBProgressHUD showClueInView:self title:@"密码未填写" duration:0.7];
                break;
            }else if (i == 3){
                [MBProgressHUD showClueInView:self title:@"密码未填写" duration:0.7];
                break;
            }else if (i == 4){
                [MBProgressHUD showClueInView:self title:@"昵称未填写" duration:0.7];
                break;
            }
        }else{
            if (i == 0) {
                if (![NSString isValidateMobile:inputV.textF.text]) {
                    [MBProgressHUD showClueInView:self title:@"手机号输入有误" duration:0.7];
                    break;
                }
                [param setObject:inputV.textF.text forKey:@"username"];
                [param setObject:inputV.textF.text forKey:@"phone"];

            }else if (i == 1){
                if ([inputV.textF.text length] < 6) {
                    [MBProgressHUD showClueInView:self title:@"验证码为6位数" duration:0.7];
                    break;
                }
                [param setObject:inputV.textF.text forKey:@"code"];
            }else if (i == 2){
                if (![NSString isValidatePassword:inputV.textF.text]) {
                    [MBProgressHUD showClueInView:self title:@"密码为6~20位字母、数字、点、下划线、减号组合" duration:0.7];
                    break;
                }else{
                    oldPassword = inputV.textF.text;
                }
            }else if (i == 3){
                if (![oldPassword isEqualToString:inputV.textF.text]) {
                    [MBProgressHUD showClueInView:self title:@"两次密码输入不一致" duration:0.7];
                    break;
                }
                [param setObject:inputV.textF.text forKey:@"password"];
            }else if (i == 4){
                if (![NSString isValidateNickName:inputV.textF.text]) {
                    [MBProgressHUD showClueInView:self title:@"昵称是2~11位中文、字母、数字、下划线或减号且不含有“掌中佛”三个字" duration:0.7];
                    break;
                }else{
                
                    if ([inputV.textF.text containsString:@"掌中佛"]) {
                        [MBProgressHUD showClueInView:self title:@"昵称是2~11位中文、字母、数字、下划线或减号且不含有“掌中佛”三个字" duration:0.7];
                        break;
                    }
                }
                [param setObject:inputV.textF.text forKey:@"nickname"];
            }
        }
        
        [inputV.textF resignFirstResponder];

    }
    
    if ([param count] < 5) {
        
        return;
    }
    
   __block NSString *password = [param objectForKey:@"password"];
    [param setObject:[password md5String] forKey:@"password"];
    
    NSDictionary *codeParam = @{@"code":param[@"code"],@"phone":param[@"phone"]};
    
    [MBProgressHUD showHUDAddedTo:self animated:YES];
    [self.registerService checkCodeByParam:codeParam
                                   success:^(NSString *code, id responseObject) {
        
                                    [self.registerService registerUserByParam:param
                                                                      success:^(NSString *code, id responseObject) {
                                        
                                                                          [MBProgressHUD hideHUDForView:self animated:NO];
                                                                          [MBProgressHUD showSuccess:@"注册成功" toView:self];
                                                                          
                                                                          BZUCUserModel *currentUser = [[BZUCUserModel alloc]init];
                                                                          currentUser.phone = [param objectForKey:@"phone"];
                                                                          currentUser.password = password;
                                                                          [[BZUCCurrentUser shareInstance]setUserModel:currentUser];
                                                                          [[self viewController].navigationController popViewControllerAnimated:YES];
                                        
                                    } failure:^(NSString *code, NSError *error) {
                                        
                                                                          [MBProgressHUD hideHUDForView:self animated:NO];
//                                                                          [MBProgressHUD showSuccess:@"网络请求失败" toView:self];
                                        
                                    }];
        
    } failure:^(NSString *code, NSError *error) {
        
         [MBProgressHUD hideHUDForView:self animated:NO];
        
    }];
    

    

}


- (void)shouldTriggerTimeKeeper:(BZUCInputV *)inputView timeKeeper:(BZBaseTimeKeeperBtn *)timeKeeper{
    
    
    
    AFNetworkReachabilityStatus status = [AFNetworkReachabilityManager sharedManager].networkReachabilityStatus;
    if (status == AFNetworkReachabilityStatusNotReachable) {
        [MBProgressHUD showClueInView:self title:@"无网络" duration:0.75];
        return;
    }

    BZUCInputV *inputV = self.inputArr[0];
    inputV.textF.text = [inputV.textF.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    
    if (![inputV.textF.text length]) {
        [MBProgressHUD showClueInView:self title:@"请输入手机号" duration:0.7];
        return;
    }
    if (![NSString isValidateMobile:inputV.textF.text]) {
        [MBProgressHUD showClueInView:self title:@"手机号输入有误" duration:0.7];
        return;
    }
    
   __block BOOL shouldBeBack = NO;
    [self.registerService getSMSCodeByPhoneNumber:[NSString stringWithFormat:@"%@",inputV.textF.text]
                                         withImei:[inputV.textF.text md5String]
                                         withCode:3
                                          success:^(NSString *code, id responseObject) {
                                           [MBProgressHUD showClueInView:self title:@"验证码发送成功" duration:0.7];
//                                          [timeKeeper stopTimers];
                                      
                                              
                                       } failure:^(NSString *code, NSError *error) {
                                           
                                           NSString *errorMessage = [error.userInfo objectForKey:NSLocalizedDescriptionKey];
                                           
                                           if (![errorMessage isEqualToString:@"手机号已注册，请更换手机号"] && ![errorMessage isEqualToString:@"无网络"] && ![errorMessage containsString:@"似乎已断开与互联网的连接"]) {
                                               [MBProgressHUD showClueInView:self title:@"验证码发送失败" duration:0.7];
                                               shouldBeBack = NO;

                                           }else{
                                           [MBProgressHUD showClueInView:self title:@"无网络" duration:0.7];
                                               shouldBeBack = YES;
                                           }
                                           [timeKeeper stopTimers];

//                                          [timeKeeper stopTimers];
                                      
                                  }];
    
    if (!shouldBeBack) {
        [timeKeeper beginTimers];
    }
    


}

@end
